<template>
  <div class="tree-node">
    <div class="node-content">
      <!-- 展开/折叠按钮 -->
      <button>
        <div
          v-if="node.children && node.children.length > 0"
          @click="toggleExpand"
        >
          <img
            class="expanded-img"
            src="./images/hiden.png"
            v-show="node.expanded"
          />
          <img
            class="hiden-img"
            src="./images/hiden.png"
            v-show="!node.expanded"
          />
        </div>
      </button>
      <!-- visible 复选框，支持中间态 -->
      <input
        type="checkbox"
        :checked="node.visible === true"
        :indeterminate="node.visible === null"
        @change="toggleVisibility"
      />
      <span>{{ node.name }}</span>
    </div>
    <!-- 递归渲染子节点 -->
    <div v-if="node.expanded" class="children">
      <TreeNode v-for="child in node.children" :key="child.id" :node="child" />
    </div>
  </div>
</template>
<script setup>
import bus from "./bus";
const props = defineProps({
  node: {
    type: Object,
    required: true,
  },
});
// 切换当前节点的展开/折叠状态
const toggleExpand = () => {
  const newExpanded = !props.node.expanded; // 简化 expanded 处理
  bus.emit("update-expanded", { node: props.node, expanded: newExpanded });
};
// 切换当前节点的显示状态
const toggleVisibility = () => {
  let newVisible;
  if (props.node.visible === null) {
    newVisible = true; // 如果是 null，默认改为 true
  } else {
    newVisible = !props.node.visible; // 切换 true <-> false
  }
  bus.emit("toggle-visibility", { node: props.node, visible: newVisible });
};
</script>
<style scoped>
.tree-node {
  margin-left: 20px;
}
.node-content {
  display: flex;
  align-items: center;
}
button {
  margin-right: 5px;
  background-color: #ffffff;
  width: 20px;
  height: 20px;
  border: 0;
}
button > div {
  width: 20px;
  height: 20px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}
button img {
  height: 20px;
}
.expanded-img {
  transform: rotate(90deg);
}
input[type="checkbox"] {
  margin-right: 10px;
}
</style>
